<template>
  <div v-loading="queueLoading" class="container">
    <div class="header">
      <div class="title">{{ title }}</div>
      <div v-auth="{ authArr: auth, key: 'edit' }" class="btns">
        <template v-if="state.editor">
          <el-button @click="handleClick(true)">{{ $t("merak.cancel") }}</el-button>
          <el-button type="primary" @click="handleClick()">{{ $t("merak.save") }}</el-button>
        </template>
        <el-button v-else type="primary" :icon="EditIcon" link style="padding: 0; min-width: auto" @click="handleClick()">
          {{ $t("merak.edit") }}
        </el-button>
      </div>
    </div>
    <div class="body">
      <div class="merak-overflow-y">
        <el-form
          ref="formRef"
          labelWidth="auto"
          :labelPosition="state.editor ? 'top' : 'right'"
          :model="formValue"
          :rules="formRules"
          :hideRequiredAsterisk="!state.editor"
        >
          <el-row :gutter="40">
            <template v-for="item in formItems">
              <el-col v-if="item.visible !== false" :span="8">
                <template v-if="item.prop === 'org_group'">
                  <MerakXFormItem
                    v-bind="item"
                    :label="$t(`staff_list.${item.prop}`)"
                    v-model:value="org_group"
                    v-model:default="org_text"
                    @change="handleFormItemChange"
                  />
                </template>
                <template v-else-if="item.prop === 'password'">
                  <MerakXFormItem
                    v-bind="item"
                    :label="$t(`staff_list.${item.prop}`)"
                    v-model:value="formValue[item.prop]"
                    v-model:default="state.password"
                    @change="handleFormItemChange"
                  />
                </template>
                <template v-else-if="item.prop === 'seniority'">
                  <MerakXFormItem
                    v-bind="item"
                    :label="$t(`staff_list.${item.prop}`)"
                    v-model:value="formValue[item.prop]"
                    v-model:default="seniority_text"
                    @change="handleFormItemChange"
                  />
                </template>
                <template v-else>
                  <MerakXFormItem
                    v-bind="item"
                    :label="$t(`staff_list.${item.prop}`)"
                    :queryOptions="field => queryOptions(field)"
                    v-model:value="formValue[item.prop]"
                    v-model:default="formValue[`${item.prop}_txt`]"
                    @change="handleFormItemChange"
                  >
                    <template #custom_mobile>
                      <template v-if="state.editor">
                        <el-row>
                          <el-col :span="9">
                            <el-form-item prop="country_code">
                              <el-select
                                class="qf_select"
                                v-model="formValue.country_code"
                                @change="() => formRef?.validateField('mobile')"
                              >
                                <el-option
                                  v-for="option in state.countryCodeOptions"
                                  :value="option.value"
                                  :label="option.label"
                                />
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span="1">
                            <div style="text-align: center">-</div>
                          </el-col>
                          <el-col :span="14">
                            <el-form-item prop="mobile">
                              <el-input v-number class="qf_input" autocomplete="new-password" v-model="formValue.mobile" @input="value => (formValue.mobile = value.replace('+', ''))" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </template>
                      <span v-else>+{{ formValue.country_code }}{{ formValue.mobile }}</span>
                    </template>
                  </MerakXFormItem>
                </template>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { getCurrentInstance, inject, ref, reactive, computed, watch, onMounted } from "vue";

import { useRoute } from "vue-router";

import useLoading from "@/hooks/useLoading";

import useDateFormat from "@/hooks/useDateFormat";

import { ElMessage, FormRules, ElButton, ElForm, ElFormItem, ElRow, ElCol, ElSelect, ElOption, ElInput } from "element-plus";

import MerakXFormItem, { MerakXFormItemOption, MerakXFormItemChangeParams } from "@/components/MerakXFormItem";

import MerakIcon from "@/components/MerakIcon/index.vue";

import {
  ComponentKeys,
  renderAge,
  renderConstellation,
  renderTwelve,
  userItems,
  newsletterItems,
  educationItems,
  jobItems,
  vacationItems,
  vacationRemainItems
} from "../formItems";

import { ResultEnum } from "@/enums/httpEnum";
import { getDictOptions, checkDuplicate, getPersonnelInfo, savePersonnelInfo } from "@/api/modules/sysManage/personnel";

import { confirmWarningMsg } from "@/utils/messageUtils";

import dayjs from "dayjs";

// 国籍关联字段
const nationalityRelatedKeys = [
  "employee_name",
  "employee_alias",
  "nationality",
  "sex",
  "birthday",
  "mobile",
  "company_email",
  "passport_no",
  "job_no",
  "username",
  "password",
  "hiredate",
  "org_group",
  "office_location_id",
  "direct_superiors",
  // 自定义的
  "country_code",
  "org_company",
  "org_department",
  "org_title",
  // 仅展示
  "paid_annual_leave",
  "remaining_annual_leave"
];

// 离职字段
const departKeys = ["left_date", "left_reason"];

// 签证字段
const visaKeys = ["visa_type", "visa_number", "visa_entity", "visa_expiration_date"];

const EditIcon = (
  <MerakIcon>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
      <path d="M5,3C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V12H19V19H5V5H12V3H5M17.78,4C17.61,4 17.43,4.07 17.3,4.2L16.08,5.41L18.58,7.91L19.8,6.7C20.06,6.44 20.06,6 19.8,5.75L18.25,4.2C18.12,4.07 17.95,4 17.78,4M15.37,6.12L8,13.5V16H10.5L17.87,8.62L15.37,6.12Z" />
    </svg>
  </MerakIcon>
);

const props = defineProps<{
  type: ComponentKeys;
}>();

const emit = defineEmits<{
  renew: [data: Record<string, any>];
}>();

const route = useRoute();

const { queueId, queueLoading } = useLoading();

const { format } = useDateFormat();

const currentInstance = getCurrentInstance();

const auth = inject("auth");
const orgOptions = inject<MerakXFormItemOption[]>("orgOptions", []);

const formRef = ref<InstanceType<typeof ElForm>>();

const state = reactive<{
  editor: boolean;
  password: string;
  copyData: Record<string, any>;
  idTypeOptions: MerakXFormItemOption[];
  constellationOptions: MerakXFormItemOption[];
  countryCodeOptions: MerakXFormItemOption[];
}>({
  editor: false,
  password: "******",
  copyData: {},
  idTypeOptions: [],
  constellationOptions: [],
  countryCodeOptions: []
});

const formValue = reactive<Record<string, any>>({});

const formRules = computed<FormRules>(() => {
  const { id } = route.query;
  return {
    employee_name: [
      {
        required: true,
        trigger: "change",
        validator: (rule, value, callback) => {
          let reg = /[\d~`!@#$%^&*()\-_=+[\]{}|;:'",<.>/?]+/g;
          if (!value) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.employee_name_valid")));
          } else if (reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.employee_name_valid_limit")));
          } else {
            callback();
          }
        }
      }
    ],
    employee_alias: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg = /[~`!@#$%^&*()\-_=+[\]{}|;:'",<.>/?]+/g;
          if (reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.employee_alias_valid_limit")));
          } else {
            callback();
          }
        }
      }
    ],
    file_no: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg = /^[\w\s]*$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.file_no_valid")));
          } else {
            callback();
          }
        }
      }
    ],
    id_no: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          let reg: RegExp = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.id_valid")));
          } else {
            callback();
          }
        }
      }
    ],
    passport_no: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          let reg: RegExp = /^[A-Za-z0-9]+$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.id_valid")));
          } else {
            callback();
          }
        }
      }
    ],
    country_code: [{ required: true, message: currentInstance?.proxy?.$t("staff_list.country_code_valid") }],
    mobile: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          let reg: RegExp;
          switch (formValue.country_code) {
            case 86:
              reg = /^1\d{10}$/;
              break;
            // case 7:
            //   reg = /^\d{10}$/;
            //   break;
            // case 375:
            //   reg = /^\d{9}$/;
            //   break;
            // case 374:
            //   reg = /^\d{8}$/;
            //   break;
            default:
              reg = /^[1-9]\d*$/;
              break;
          }
          if (!value) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.mobile_valid")));
          } else if (reg.test(value)) {
            callback();
          } else {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.mobile_valid_limit")));
          }
        }
      }
    ],
    phone_ext: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg = /^[1-9]\d*$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.phone_valid")));
          } else {
            callback();
          }
        }
      }
    ],
    phone: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg = /^[1-9]\d*$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.phone_valid")));
          } else {
            callback();
          }
        }
      }
    ],
    personal_email: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg =
            /^[A-Za-z0-9]+([-._][A-Za-z0-9]+)*@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z]{2,6}|[A-Za-z]{2,4}\.[A-Za-z]{2,3})$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.email_valid")));
          }
          callback();
        }
      }
    ],
    company_email: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg =
            /^[A-Za-z0-9]+([-._][A-Za-z0-9]+)*@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z]{2,6}|[A-Za-z]{2,4}\.[A-Za-z]{2,3})$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.email_valid")));
          }
          callback();
        }
      }
    ],
    job_no: [
      {
        required: true,
        trigger: "blur",
        validator: (rule, value, callback) => {
          const reg = /^[0-9]*$/;
          if (!value) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.job_no_valid")));
          } else if (reg.test(value)) {
            checkDuplicate({ field: "job_no", value, user_id: id as string }).then(({ code, message }) => {
              if (code == ResultEnum.SUCCESS) {
                callback();
              } else {
                callback(new Error(message as string));
              }
            });
          } else {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.integer_valid")));
          }
        }
      }
    ],
    username: [
      {
        required: true,
        validator: (rule, value, callback) => {
          const reg = /^[\w\s]*$/;
          if (!value) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.username_valid")));
          } else if (reg.test(value)) {
            callback();
          } else {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.username_valid_limit")));
          }
        }
      },
      {
        trigger: "blur",
        validator: (rule, value, callback) => {
          checkDuplicate({ field: "username", value, user_id: id as string }).then(({ code, message }) => {
            if (code == ResultEnum.SUCCESS) {
              callback();
            } else {
              callback(new Error(message as string));
            }
          });
        }
      }
    ],
    password: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg = /^[a-zA-Z]\w{5,17}$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.password_valid_limit")));
          } else {
            callback();
          }
        }
      }
    ],
    paid_annual_leave: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg = /^[1-9]\d*$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.integer_valid")));
          } else {
            callback();
          }
        }
      }
    ],
    paid_sick_leave: [
      {
        trigger: "change",
        validator: (rule, value, callback) => {
          const reg = /^[1-9]\d*$/;
          if (!!value && !reg.test(value)) {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.integer_valid")));
          } else {
            callback();
          }
        }
      }
    ]
  };
});

const formItems = computed(() => {
  const readonly = !state.editor;
  switch (props.type) {
    case ComponentKeys.user:
      return [...userItems].map(item => {
        let visible = true;
        if (!nationalityRelatedKeys.includes(item.prop)) {
          visible = formValue.nationality === "china";
        }
        if (item.prop === "id_type") {
          return {
            ...item,
            visible,
            readonly,
            options: state.idTypeOptions.filter(option =>
              formValue.nationality === "china" ? true : [0, 6].includes(option.value as number)
            )
          };
        }
        if (item.prop === "constellation") {
          return { ...item, visible, readonly, options: state.constellationOptions };
        }
        return { ...item, visible, readonly };
      });
    case ComponentKeys.newsletter:
      return [...newsletterItems].map(item => {
        if (!nationalityRelatedKeys.includes(item.prop)) {
          const visible = formValue.nationality === "china";
          return { ...item, readonly, visible };
        }
        return { ...item, readonly };
      });
    case ComponentKeys.education:
      return [...educationItems].map(item => {
        if (!nationalityRelatedKeys.includes(item.prop)) {
          const visible = formValue.nationality === "china";
          return { ...item, readonly, visible };
        }
        return { ...item, readonly };
      });
    case ComponentKeys.job:
      return [
        ...[...jobItems].map(item => {
          let visible = true;
          if (!nationalityRelatedKeys.includes(item.prop)) {
            visible = formValue.nationality === "china";
          }
          if (departKeys.includes(item.prop)) {
            visible = formValue.status === 0 || formValue.status === 3;
          }
          if (visaKeys.includes(item.prop)) {
            visible = formValue.nationality === "china" && formValue.office_location_id === 4;
          }
          if (item.type === "input" && item.prop === "password") {
            const props = { ...(item.props ?? {}) };
            props.placeholder = state.password;
            return { ...item, visible, readonly, props };
          }
          if (item.prop === "org_group") {
            return { ...item, visible, options: orgOptions, readonly };
          }
          if (item.prop === "job_no") {
            return { ...item, visible, readonly: true };
          }
          return { ...item, visible, readonly };
        }),
        ...[...vacationItems].map(item => {
          if (!nationalityRelatedKeys.includes(item.prop)) {
            const visible = formValue.nationality === "china";
            return { ...item, visible, readonly };
          }
          return { ...item, readonly };
        }),
        ...[...vacationRemainItems].map(item => {
          if (!nationalityRelatedKeys.includes(item.prop)) {
            const visible = formValue.nationality === "china";
            return { ...item, visible };
          }
          return { ...item };
        })
      ];
    default:
      return [];
  }
});

const title = computed(() => {
  switch (props.type) {
    case ComponentKeys.user:
      return currentInstance?.proxy?.$t("staff_list.personal_info");
    case ComponentKeys.newsletter:
      return currentInstance?.proxy?.$t("staff_list.newsletter_info");
    case ComponentKeys.education:
      return currentInstance?.proxy?.$t("staff_list.education_info");
    case ComponentKeys.job:
      return currentInstance?.proxy?.$t("staff_list.on_the_job_info");
    default:
      return;
  }
});

const org_group = computed({
  get() {
    const values: string[] = [];
    const options = formItems.value.find(item => item.prop === "org_group")?.options ?? [];
    const queryValue = (value: string, level: number, options: MerakXFormItemOption[]) => {
      for (let option of options) {
        const optionValues = (option.value as string).split("-");
        if (optionValues.length === level && optionValues[optionValues.length - 1] === value) {
          return option.value;
        } else if (!!option.children?.length && !!queryValue(value, level, option.children)) {
          return queryValue(value, level, option.children);
        }
      }
    };
    const companyValues = [...(formValue.org_company ?? [])]
      .map(value => queryValue(value.toString(), 1, options))
      .filter(Boolean) as string[];
    const departmentValues = [...(formValue.org_department ?? [])]
      .map(value => queryValue(value.toString(), 2, options))
      .filter(Boolean) as string[];
    const titleValues = [...(formValue.org_title ?? [])]
      .map(value => queryValue(value.toString(), 3, options))
      .filter(Boolean) as string[];
    // 遍历公司id的集合
    for (let companyValue of companyValues) {
      // 判断部门id的集合中是否有存在该公司下的部门
      if (departmentValues.some(departmentValue => departmentValue.includes(`${companyValue}-`))) {
        // 遍历部门id的集合
        for (let departmentValue of departmentValues) {
          // 判断部门存在该公司下
          if (departmentValue.includes(`${companyValue}-`)) {
            // 判断岗位id的集合中是否有存在该部门下的岗位
            if (titleValues.some(titleValue => titleValue.includes(`${departmentValue}-`))) {
              // 遍历岗位id的集合
              for (let titleValue of titleValues) {
                // 判断岗位存在该部门下
                if (titleValue.includes(`${departmentValue}-`)) {
                  values.push(titleValue);
                }
              }
            } else {
              // 当部门存在该公司下并且岗位集合中不存在该部门的岗位
              values.push(departmentValue);
            }
          }
        }
      } else {
        // 当部门集合中不存在该公司的部门
        values.push(companyValue);
      }
    }
    return [...new Set(values)];
  },
  set(values) {
    const org_company: number[] = [];
    const org_department: number[] = [];
    const org_title: number[] = [];
    for (let value of values) {
      const [company, department, title] = value.split("-");
      if (!!company) {
        org_company.push(Number(company));
      }
      if (!!department) {
        org_department.push(Number(department));
      }
      if (!!title) {
        org_title.push(Number(title));
      }
    }
    formValue.org_company = org_company;
    formValue.org_department = org_department;
    formValue.org_title = org_title;
  }
});

const org_text = computed(() => {
  const arr: string[] = [];
  const queryLabel = (options: MerakXFormItemOption[], value: string) => {
    for (let option of options) {
      if (option.value === value) {
        return [option.label];
      }
      if (!!option.children?.length) {
        const node = queryLabel(option.children, value);
        if (!!node) {
          return [option.label, ...node];
        }
      }
    }
  };
  for (let value of org_group.value) {
    arr.push(queryLabel(orgOptions, value).join("/"));
  }
  return !!arr.length ? arr.join(", ") : "-";
});

const seniority_text = computed(() => {
  let text: string = "";
  const year = Math.floor(Number(formValue.seniority ?? 0) / 12);
  const mouth = Number(formValue.seniority ?? 0) % 12;
  if (year > 0) {
    text += `${year}${currentInstance?.proxy?.$t("merak.year")}`;
  }
  if (mouth > 0) {
    text += `${mouth > 9 ? "" : "0"}${mouth}${currentInstance?.proxy?.$t("merak.format_month")}`;
  }
  return !!text ? text : "-";
});

const handleClick = (cancel: boolean = false) => {
  if (cancel) {
    formRef.value?.clearValidate();
    for (let key of Object.keys(state.copyData)) {
      formValue[key] = state.copyData[key];
    }
    state.editor = false;
  } else if (state.editor) {
    formRef.value
      ?.validate()
      .then(() => {
        confirmWarningMsg({
          msg: currentInstance?.proxy?.$t("staff_list.save_employee_info_warning") ?? "",
          callback: (val: string) => {
            if (val === "confirm") {
              const data: Record<string, any> = {};
              for (let key of Object.keys(formValue)) {
                if (key.includes("_txt")) {
                  continue;
                }
                const isKey = formItems.value.some(item => {
                  if (item.prop === "org_group") {
                    return ["org_company", "org_department", "org_title"].includes(key);
                  }
                  if (item.prop === "mobile") {
                    return ["country_code", "mobile"].includes(key);
                  }
                  return item.prop === key;
                });
                if (isKey) {
                  data[key] = formValue[key];
                }
              }
              data.user_id = route.query.id as string;
              savePersonnelInfo(data).then(({ code, message }) => {
                if (code == ResultEnum.SUCCESS) {
                  const renewData: Record<string, any> = {};
                  for (let key of Object.keys(formValue)) {
                    if (typeof formValue[key] !== "number" && !formValue[key]) continue;
                    if (key === "mobile" && !!formValue.country_code) {
                      renewData[key] = `+${formValue.country_code}${formValue[key]}`;
                      continue;
                    }
                    if (key === "office_location_id" && !!formValue.office_location_id_txt) {
                      renewData[key] = formValue.office_location_id_txt;
                      continue;
                    }
                    if (key === "org_title" && !!formValue.org_title_txt) {
                      renewData.org_title = formValue.org_title_txt;
                      continue;
                    }
                    if (["employee_name", "sex", "job_no", "nationality"].includes(key)) {
                      renewData[key] = formValue[key];
                      continue;
                    }
                  }
                  emit("renew", renewData);
                  state.editor = false;
                  ElMessage.success(currentInstance?.proxy?.$t("staff_list.save_employee_info_success"));
                } else if (typeof message === "string") {
                  ElMessage.error(message);
                } else {
                  const msg = Object.values(message)?.[0];
                  ElMessage.error(msg);
                }
              });
            }
          }
        });
      })
      .catch(err => {
        const first = Object.keys(err)?.[0];
        if (!!first) {
          formRef.value?.scrollToField(first);
        }
      });
  } else {
    for (let key of Object.keys(formValue)) {
      state.copyData[key] = formValue[key];
    }
    state.editor = true;
  }
};

const handleFormItemChange = (params: MerakXFormItemChangeParams) => {
  switch (params.type) {
    case "input":
      if (!!params.data) {
        formValue[params.prop] = params.data.trim();
      }
    case "select":
      if (!!params.data?.label) {
        formValue[`${params.prop}_txt`] = params.data?.label;
      }
      break;
    case "treeSelect":
      if (params.prop === "org_group" && !!params.data?.label && Array.isArray(params.data.label)) {
        formValue.org_title_txt = params.data.label
          .map((item: { label: string }) => item.label.split("/")?.[2])
          .filter(Boolean)
          .join(",");
      }
    default:
      break;
  }
};

const queryOptions = async (key?: string) => {
  if (!key) return;
  return getDictOptions({ key }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      return [...data].map(item => ({ value: item.key, label: item.value }));
    }
    return;
  });
};

// 国籍选择联动
watch(
  () => formValue.nationality,
  () => {
    if (formValue.nationality === "china") {
      ["household_registration_type", "marriage", "fertility"].forEach(key => {
        if (!formValue[key] && typeof formValue[key] !== "number") {
          formValue[key] = 0;
        }
      });
    } else {
      Object.keys(formValue).forEach(key => {
        if (!nationalityRelatedKeys.includes(key) && !nationalityRelatedKeys.map(key => `${key}_txt`).includes(key)) {
          formValue[key] = undefined;
        }
      });
    }
  },
  { immediate: true }
);

// 签证联动
watch(
  [() => formValue.nationality, () => formValue.office_location_id],
  () => {
    if (formValue.nationality !== "china" || formValue.office_location_id !== 4) {
      Object.keys(formValue).forEach(key => {
        if (visaKeys.includes(key)) {
          formValue[key] = undefined;
        }
      });
    }
  },
  { immediate: true }
);

// 员工状态联动
watch(
  () => formValue.status,
  () => {
    Object.keys(formValue).forEach(key => {
      if (formValue.status !== 0 && formValue.status !== 3 && departKeys.includes(key)) {
        formValue[key] = undefined;
      }
    });
  }
);

// 生日联动
watch([() => formValue.birthday, () => formValue.nationality], () => {
  if (!formValue.birthday || formValue.nationality !== "china") return;
  formValue.age = renderAge(formValue.birthday);
  formValue.twelve = currentInstance?.proxy?.$t(`staff_list.${renderTwelve(formValue.birthday)}`);
  formValue.constellation = renderConstellation(formValue.birthday).key;
});

// 证件号码重新校验
watch(
  () => formValue.id_type,
  () => {
    if (props.type === ComponentKeys.user && state.editor) {
      formRef.value?.validateField("id_no");
    }
  }
);

// 转正日期联动
watch([() => formValue.hiredate, () => formValue.probation], () => {
  if (!formValue.hiredate || typeof formValue.probation !== "number") return;
  formValue.confirmation_date = dayjs(formValue.hiredate).add(formValue.probation, "month").format(format);
});

// 司龄联动
watch([() => formValue.hiredate, () => formValue.nationality], () => {
  if (!formValue.hiredate || formValue.nationality !== "china") return;
  formValue.company_seniority = renderAge(formValue.hiredate);
});

// 工龄联动
// watch(
//   () => formValue.first_job_date,
//   () => {
//     if (!formValue.first_job_date) return;
//     formValue.seniority = renderAge(formValue.first_job_date);
//   }
// );

// 合同类型联动;
watch(
  () => formValue.contract_type,
  () => {
    if (formValue.contract_type === 3) {
      delete formValue.contract_period;
    }
  }
);

onMounted(() => {
  const { id } = route.query;
  if (!!id) {
    getPersonnelInfo(id as string, queueId.value).then(({ code, data }) => {
      if (code == ResultEnum.SUCCESS) {
        for (let key of Object.keys(data)) {
          formValue[key] = data[key];
        }
      }
    });
  }
  if (props.type === ComponentKeys.user) {
    queryOptions("id_type").then(data => {
      state.idTypeOptions = [...(data ?? [])];
    });
    queryOptions("constellation").then(data => {
      state.constellationOptions = [...(data ?? [])];
    });
  }
  if (props.type === ComponentKeys.newsletter) {
    queryOptions("country_code").then(data => {
      state.countryCodeOptions = [...(data ?? [])];
    });
  }
});
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: var(--merak-padding);
    height: var(--merak-button-size);
    font-size: 16px;
  }
  .body {
    flex: auto;
    min-height: 0;
    .el-form.el-form--label-right {
      :deep(.el-form-item__label-wrap) {
        margin-right: 30px;
      }
    }
  }
}
</style>
